package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ApUserSearchService searchService;

    /**
     * es文章自动分页检索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //检查参数
        if (dto==null|| StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //异步调用保存搜索记录
        ApUser apUser = ApThreadLocalUtil.getApUser();
        if (apUser!=null&&dto.getSearchWords()!=null){
            searchService.insert(dto.getSearchWords(),apUser.getId());
        }
        //设置查询条件
        SearchRequest request=new SearchRequest("app_info_article");
        SearchSourceBuilder builder=new SearchSourceBuilder();
        //布尔查询
        BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery();
        //关键字查询
        boolQueryBuilder.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
        .field("title").field("content").defaultOperator(Operator.OR));
        //查询时间
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //分页查询
        builder.from(0).size(dto.getPageSize());
        //按照发布时间倒序查询
        builder.sort("publishTime", SortOrder.DESC);
        //高亮字段设置
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);
        //查询条件封装
        builder.query(boolQueryBuilder);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //结果封装返回
        List<Map> list = getResponse(response);

        return ResponseResult.okResult(list);
    }

    /**
     * 相应结果封装
     * @param response
     * @return
     */
    private List<Map> getResponse(SearchResponse response) {
        List<Map> list=new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            Map map = JSON.parseObject(source, Map.class);
            //处理高亮
            if (hit.getHighlightFields()!=null&&hit.getHighlightFields().size()>0){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",title);
            }else {
                //原始标题
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return list;
    }
}
